package cn.sc.summer.mybatis.strategy.basestage;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.sc.summer.mybatis.model.TableBaseConfig;
import cn.sc.summer.mybatis.model.TablePrimary;
import cn.sc.summer.constant.service.Support;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 类名：sql语句拼接工具类，默认实现为mysql类型
 *
 * @author a-xin
 * @date 2024/8/30 14:09
 */
@Slf4j
public abstract class SqlUtil implements Support {

    private static final long serialVersionUID = -3620862974963913705L;

    /**
     * 获取更新主键Sql
     *
     * @param tablePrimaries 表主键信息
     * @return 执行Sql信息
     */
    public String getUpdatePrimaryIdSql(List<TablePrimary> tablePrimaries) {
        return tablePrimaries.stream().map(tablePrimaryId -> {
            StringBuilder stringBuilder = new StringBuilder("ALTER TABLE `");
            stringBuilder.append(tablePrimaryId.getTableName()).append("`");
            stringBuilder.append(" DROP PRIMARY KEY");
            List<String> primaryIds = tablePrimaryId.getPrimaryIds();
            if (CollUtil.isNotEmpty(primaryIds)) {
                stringBuilder.append(", ADD PRIMARY KEY (");
                String primaryKey = primaryIds.stream().map(primaryId -> "`" + primaryId + "`")
                        .collect(Collectors.joining(","));
                stringBuilder.append(primaryKey).append(") USING BTREE");
            }
            return stringBuilder.toString();
        }).collect(Collectors.joining(";"));
    }

    /**
     * 获取mysql环境配置
     *
     * @param tableBaseConfig 环境配置
     * @param tableName       数据库表名
     * @return 环境sql
     */
    public String getEnvSQL(TableBaseConfig tableBaseConfig, String tableName) {
        StringBuilder envSql = new StringBuilder();
        if (tableBaseConfig.getEnable()) {
            envSql.append("SET NAMES ").append(tableBaseConfig.getCharSet()).append(";");
            envSql.append("SET FOREIGN_KEY_CHECKS = 0;");
        }
        envSql.append("DROP TABLE IF EXISTS `").append(tableName).append("`;");
        return envSql.toString();
    }

    /**
     * 获取新增数据库表sql信息
     *
     * @param tableName       表名称
     * @param field           字段sql
     * @param primary         主键字段
     * @param comment         表注释
     * @param tableBaseConfig 表配置信息
     * @return 完整sql语句
     */
    public String getTableAddSql(String tableName, String field, List<String> primary, String comment, TableBaseConfig tableBaseConfig) {
        String primaryKey = primary.stream().map(item -> "`" + item + "`")
                .collect(Collectors.joining(","));
        StringBuilder tableAddSql = new StringBuilder("CREATE TABLE ");
        tableAddSql.append("`").append(tableName).append("` (")
                .append(field).append(", PRIMARY KEY (").append(primaryKey).append("))");
        if (tableBaseConfig.getEnable()) {
            tableAddSql.append(" ENGINE = ").append(tableBaseConfig.getEngine()).append(" DEFAULT")
                    .append(" CHARSET = ").append(tableBaseConfig.getCharSet())
                    .append(" COLLATE = ").append(tableBaseConfig.getCollate());
        }
        if (CharSequenceUtil.isNotBlank(comment)) {
            tableAddSql.append(" COMMENT = '").append(comment).append("'");
        }
        tableAddSql.append(";");
        return tableAddSql.toString();
    }

    /**
     * 获取修改表注释sql
     *
     * @param tableName 表名称
     * @param comment   表注释信息
     * @return 修改表注释完整sql
     */
    public String getTableUpdateSql(String tableName, String comment) {
        return "ALTER TABLE " + tableName + " COMMENT '" + comment + "'";
    }

    /**
     * 获取修改表名称sql
     *
     * @param oldTableName 表名称
     * @param newTableName 表注释信息
     * @return 修改表注释完整sql
     */
    public String getTableRenameSql(String oldTableName, String newTableName) {
        return "RENAME TABLE " + oldTableName + " TO " + newTableName + ";";
    }

    /**
     * 获取数据库表字段sql（新增或更新都可使用）
     *
     * @param fieldName 字段名称
     * @param fieldType 字段类型
     * @param comment   字段注释信息
     * @param nullable  该字段是否可以为空
     * @return 字段sql（新增或更新都可使用）
     */
    public String getFieldSql(String fieldName, String fieldType, String comment, Boolean nullable) {
        StringBuilder fieldSql = new StringBuilder("`");
        fieldSql.append(fieldName).append("`");
        fieldSql.append(" ").append(fieldType);
        if (!nullable) {
            fieldSql.append(" NOT NULL");
        } else {
            fieldSql.append(" NULL");
        }
        if (CharSequenceUtil.isNotBlank(comment)) {
            fieldSql.append(" COMMENT '").append(comment).append("'");
        }
        return fieldSql.toString();
    }

    /**
     * 获取表字段新增sql
     *
     * @param tableName 表名称
     * @param fieldSql  字段sql
     * @return 添加字段sql
     */
    public String getFieldAddSql(String tableName, String fieldSql) {
        return "ALTER TABLE" + " `" + tableName + "`" +
                " ADD COLUMN " + fieldSql + ";";
    }

    /**
     * 获取表字段更新sql
     *
     * @param tableName 表名称
     * @param fieldSql  字段sql
     * @return 更新字段sql
     */
    public String getFieldUpdateSql(String tableName, String fieldSql) {
        return "ALTER TABLE" + " `" + tableName + "`" +
                " MODIFY COLUMN " + fieldSql + ";";
    }

    /**
     * 获取表字段删除sql
     *
     * @param tableName 表名称
     * @param fieldName 字段sql
     * @return 删除字段sql
     */
    public String getFieldDeleteSql(String tableName, String fieldName) {
        return "ALTER TABLE" + " `" + tableName + "`" +
                " DROP COLUMN `" + fieldName + "`;";
    }

}
